package tako.wisers.com.android.apis.handler;

import android.view.KeyEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import tako.wisers.com.android.apis.R;
import tako.wisers.com.android.apis.activity.Tako;
import tako.wisers.com.android.apis.event.Event;
import tako.wisers.com.android.apis.event.EventBus;
import tako.wisers.com.android.apis.event.SearchEvent;
import tako.wisers.com.android.apis.location.GPSManager;
import tako.wisers.com.android.apis.util.Global;

public class SearchHandler extends TakoHandler implements Handler<Event> {

	private AutoCompleteTextView editorText;

	public SearchHandler(Tako tako) {
		super(tako);
	}

	@Override
	public void execute(Event event) {
		editorText = (AutoCompleteTextView) tako.findViewById(R.id.keyword);
		if (event instanceof SearchEvent
				&& event.getType() == Event.EVENT_KEY_DOWN) {
			String keyword = editorText.getText().toString();
			if (keyword == null || keyword.equals(""))
				return;
			SearchEvent kEvent = (SearchEvent) event;
			if (kEvent.getKeyCoed() == KeyEvent.KEYCODE_ENTER) {
				if (tako.getTopButtonItem().getHandler().equals(
						Global.NEWS_HANDLER)) {
					mhandler.sendMessage(mhandler
							.obtainMessage(Event.EVENT_KEY_DOWN));
				}
				Event topEvent = new Event(tako.getTopButtonItem().getId(),
						Event.EVENT_CLICK, true);
				EventBus.getInstance().executeEvent(topEvent);
			}
		} else if (event.getType() == Event.EVENT_CLICK) {
			mhandler.sendMessage(mhandler.obtainMessage(Event.EVENT_CLICK));
		}
	}

	private android.os.Handler mhandler = new android.os.Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Event.EVENT_KEY_DOWN:
				String keyword = editorText.getText().toString();
				GPSManager gpsListener = GPSManager.getInstance();
				gpsListener.setLocationByName(keyword);
				break;
			case Event.EVENT_CLICK:
				View keyword_bar = tako.findViewById(R.id.bar_keyword);
				keyword_bar.setVisibility(keyword_bar.getVisibility() ^ 8);
				View topBar = tako.findViewById(R.id.bar_other);
				topBar.setVisibility(topBar.getVisibility() ^ 8);
				break;
			}
			tako.dismissDialog();
		}
	};

}
